#pragma once

#include <iostream>
#include <pthread.h>
#include <signal.h>
#include "TcpServer.hpp"
#include "Log.hpp"
#include "Protocol.hpp"

#define PORT 8081

class HttpServer
{
public:
    HttpServer(int _port = PORT) :
        port(_port),
        tcp_server(nullptr),
        stop(false)
    {}

    void InitServer()
    {
        //信号SIGPIPE需要忽略，如果不忽略，在写入的时候，可能会使server崩溃
        signal(SIGPIPE, SIG_IGN);
        tcp_server = TcpServer::getinstance(port);
    }

    void Loop()
    {
        LOG(INFO, "Loop Begin");
        int listen_sock = tcp_server->Sock();
        while (!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(listen_sock, (struct sockaddr*)&peer, &len);
            if (sock < 0)
            {
                continue;
            }
            LOG(INFO, "Get a new link");
            int* _sock = new int(sock);
            pthread_t tid;
            pthread_create(&tid, nullptr, Entrance::HandlerRequest, _sock);
            pthread_detach(tid);
        }
    }


    ~HttpServer()
    {}


private:
    int port;
    TcpServer* tcp_server;
    bool stop;
};